<?php
namespace Zxf5115\Laravel\Dictionary\Models\Common;

use Illuminate\Support\Facades\Redis;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Zxf5115\Laravel\Kernel\Models\Base;

/**
 * @author zhangxiaofei [<1326336909@qq.com>]
 * @dateTime 2025-09-23
 *
 * 字典模型类
 */
class Dictionary extends Base
{
  /**
   * 数据库表名
   */
  public $table = "system_dictionary";

  /**
   * 批量赋值允许的字段
   */
  public $fillable = [
    'id',
  ];

  /**
   * 需要隐藏的字段
   */
  public $hidden = [
    'update_time'
  ];

  /**
   * 只查询字典标题数据的有效作用域
   *
   * @param Builder $query 查询对象
   * @param string $title 字典标题数据
   * @return Builder 查询对象
   */
  public function scopeWhereTitle(Builder $query, string $title) : Builder
  {
    return $query->where(['title' => $title, 'status' => 1]);
  }

  // 关联函数 ------------------------------------------------------

  /**
   * 字典与字典参数的关联
   *
   * @return [关联对象]
   */
  public function parameter() : HasMany
  {
    return $this->hasMany(
      'Zxf5115\Laravel\Dictionary\Models\Common\Dictionary\Parameter',
      'dictionary_id',
      'id'
    )->orderBy('sort', 'desc');
  }


  /**
   * 事件侦听方法
   *
   * @return [type]
   */
  public static function boot()
  {
    parent::boot();

    // 数据删除后清除对应缓存，保持一致性后清除缓存
    static::deleted(function (self $model) : void {
      Redis::connection('cache')->del(config('key.redis.dictionary'));
    });
  }
}
